<template>
	<!-- 不能用v-if (i: 每个tab页的专属下标;  index: 当前tab的下标; 申明在 MescrollMoreItemMixin )-->
	<view v-show="i === index">
		<!-- top="120"下拉布局往下偏移,防止被悬浮菜单遮住 -->
		<!-- ref动态生成: 字节跳动小程序编辑器不支持一个页面存在相同的ref (如不考虑字节跳动小程序可固定值为 ref="mescrollRef") -->
		<mescroll-body :ref="'mescrollRef'+i" :top="topHeight+'rpx'" @init="mescrollInit" :down="downOption"
			@down="downCallback" :up="upOption" @up="upCallback" @emptyclick="emptyClick">
			<!-- 数据列表 -->
			<storeGoods :goodList="goods" @onchangeIsBest="onchangeIsBest" @batchUpdateShow="batchUpdateShow"
				@selected="selected" @goodsDetail="goodsDetail" @putShell="putShell" :current="current"
				:isEdit="isEdit"></storeGoods>
		</mescroll-body>
		<u-popup v-model="zoneData.show" mode="center" :closeable='true' :mask-close-able="false" class="popup">
			<view class="title">{{$t("goods.joinTheZone")}}</view> <!-- 加入专区 -->
			<view class="type">
				<view>{{$t("goods.selectArea")}}：</view><!-- 选择专区 -->
				<picker @change="bindPickerChange" :value="index" :range="zhuanquList" range-key="name">
					<view class="picker acea-row row-between-wrapper">
						<view class='reason'>{{zhuanquList[zoneData.idx].name}}</view>
						<text class='iconfont iconarrow-right1'></text>
					</view>
				</picker>
			</view>
			<view class="btntype">
				<view class="btn" @tap="clear(0)">{{$t("publicLang.cancel")}}</view>
				<view class="btn pushBtn" @tap="addZhuanqu">{{$t("publicLang.sure")}}</view>
			</view>
		</u-popup>
		<!-- 修改价格 -->
		<u-popup v-model="priceData.priceShow" mode="center" :closeable='true' :mask-close-able="false" class="popup">
			<view class="title">{{$t("goods.modifyThePrice")}}</view>
			<view class="type">
				<view>{{$t("goods.methodToModifyThePrice")}}：</view>
				<!--价格修改方式-->
				<picker @change="bindPriceChange" :value="index" :range="priceType" range-key="name" v-if="index==0">
					<view class="picker acea-row row-between-wrapper">
						<view class='reason'>{{priceType[priceData.idx1].name}}</view>
						<text class='iconfont iconarrow-right1'></text>
					</view>
				</picker>
				<picker @change="bindPriceChange" :value="index" :range="buildAddType" range-key="name" v-if="index==1">
					<view class="picker acea-row row-between-wrapper">
						<view class='reason'>{{buildAddType[priceData.idx1].name}}</view>
						<text class='iconfont iconarrow-right1'></text>
					</view>
				</picker>
			</view>
			<view class="ratio">
				<input type="digit" class="uni-input" @input="checkInputFun" v-model="priceData.ratio"
					:placeholder="$t('goods.pleaseEnterMarkupRateDiscount')">
				<!--请输入加价率/折扣-->
				<!-- <view v-if="priceData.value" class="reason">{{priceData.value}}</view> -->
			</view>
			<view class="btntype">
				<view class="btn pushBtn" v-if="index==0" @click="productResetPrice">
					{{$t("goods.restoreDefaultMarkupRate")}}
				</view>
				<!--恢复默认加价率-->
				<view class="btn" @tap="clear(1)">{{$t("publicLang.cancel")}}</view>
				<view class="btn pushBtn" @click="batchPrice">{{$t("publicLang.sure")}}</view>
			</view>
		</u-popup>
		<u-popup v-model="show" mode="bottom">
			<view :style="{paddingBottom: `${bottomLift}px`}">
				<view class="batchButton" @click="bacthRecommend(1)">{{$t("goods.bulkRecommendation")}}</view>
				<!--批量推荐-->
				<view class="batchButton" @click="bacthRecommend(0)">{{$t("goods.cancelRecommendationsInBulk")}}</view>
				<!--批量取消推荐-->
				<view class="batchButton" @click="bacthRecommend(3)">{{$t("goods.applyToJoinCloudWarehouse")}}</view>
				<!--申请加入云仓-->
				<view class="batchButton" @click="show = false">{{$t("goods.closure")}}</view>
				<!--关闭-->
			</view>
		</u-popup>
	</view>
</template>

<script>
	import storeGoods from "@/components/store-goods/store-goods.vue";
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import MescrollMoreItemMixin from "@/components/mescroll-uni/mixins/mescroll-more-item.js";
	import {
		storeGoodsApi,
		productIsshow,
		buildGoodsApi,
		batchIsBestApi,
		batchIsShowApi,
		zoneList,
		zoneProductAdd,
		batchUpdatePrice,
		merchantStoreProductIsBest,
		transferCloud
	} from "@/api/storeGoods.js";
	import {
		formatTime
	} from "@/utils/common.js";
	let app = getApp();
	export default {
		components: {
			storeGoods,
		},
		mixins: [MescrollMixin, MescrollMoreItemMixin], // 注意此处还需使用MescrollMoreItemMixin (必须写在MescrollMixin后面)
		props: {
			i: Number, // 每个tab页的专属下标 (除了支付宝小程序必须在这里定义, 其他平台都可不用写, 因为已在MescrollMoreItemMixin定义)
			current: Number,
			// editCheckAll: Function,
			tableFrom: Object,
			// change: Function,
			isEdit: Boolean, // 是否显示编辑选择
			checkStatus: Boolean, // 是否显示编辑选择
			index: {
				// 当前tab的下标 (除了支付宝小程序必须在这里定义, 其他平台都可不用写, 因为已在MescrollMoreItemMixin定义)
				type: Number,
				default () {
					return 0;
				},
			},
			tabs: {
				// 为了请求数据,演示用,可根据自己的项目判断是否要传
				type: Array,
				default () {
					return [];
				},
			},
		},
		computed: {
			priceType() {
				return [{
						name: this.$t('goods.costMarkup'), // 成本加价率
						id: 3
					},
					{
						name: this.$t('goods.originalPriceDiscount'), // 原价折扣
						id: 4
					},
				]
			},
			buildAddType() {
				return [{
					name: this.$t('goods.originalPriceDiscount'), // 原价折扣
					id: 4
				}]
			}
		},
		data() {
			return {
				downOption: {
					textInOffset: this.$t('publicLang.pullDownToRefresh'), // 下拉的距离在offset范围内的提示文本
					textOutOffset: this.$t('publicLang.releaseUpdate'), // 下拉的距离大于offset范围的提示文本
					textLoading: this.$t('publicLang.loading'), // 加载中的提示文本
					textSuccess: this.$t('publicLang.loadedSuccessfully'), // 加载成功的文本
					textErr: this.$t('publicLang.failedToLoad'), // 加载失败的文本
					auto: false, // 不自动加载 (mixin已处理第一个tab触发downCallback)
				},
				upOption: {
					textLoading: this.$t('publicLang.loading'), // 加载中的提示文本
					auto: false, // 不自动加载
					page: {
						num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
						size: 20, // 每页数据的数量
					},
					noMoreSize: 4, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
					empty: {
						tip: this.$t('publicLang.empty') // 提示
						// btnText: "去看看",
					},
				},
				topHeight: 0,
				goods: [], //列表数据
				productIdList: [],
				zhuanquList: [],
				priceData: {
					productType: 1,
					idx1: 0,
					type: 3,
					ratio: "",
					priceShow: false,
				},
				zoneData: {
					zoneId: "",
					idx: 0,
					show: false,
				},
				bottomLift: app.globalData.bottomLift,
				show: false
			};
		},
		mounted() {
			console.info(this, 123)
			// #ifdef MP
			this.topHeight = app.globalData.navHeight + 296;
			// #endif
			// #ifndef MP
			this.topHeight = 96 + 296;
			// #endif
			if (this.i == this.index) {
				this.getZhuanQuList();
			}

		},
		methods: {
			/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
			upCallback(page) {
				// this.i: 每个tab页的专属下标
				// this.index: 当前tab的下标
				//   this.mescroll.endSuccess(2);
				var _this = this;
				console.log(this.index)
				this.$nextTick(function() {
					this.priceData.type = this.index == 0 ? 3 : 4;
					this.priceData.productType = this.index == 0 ? 1 : 2
					if (this.i == this.index) {
						var objData = this.tableFrom;
						this.tableFrom.page = page.num;
						this.tableFrom.type = this.tabs[this.current].value;
						let data1 = JSON.parse(JSON.stringify(objData));
						Object.keys(data1).forEach((item) => {
							if (!data1[item]) delete data1[item];
						});
						if (this.index == 0) {
							storeGoodsApi(data1)
								.then((res) => {
									var data = res.data.list;
									if (page.num == 1) _this.goods = [];
									data.map((item) => {
										item.isSelect = false;
									});
									if (data.length > 0) {
										this.$emit("editCheckAll", false);
									}
									_this.goods = _this.goods.concat(data);
									_this.mescroll.endBySize(data.length, res.data.total);
								})
								.catch((e) => {
									_this.mescroll.endErr();
									_this.$util.Tips({
										title: e
									});
								});
						} else {
							buildGoodsApi(data1).then((res) => {
								var data = res.data.list;
								data.map((item) => {
									item.isSelect = false;
								});
								if (page.num == 1) _this.goods = [];
								if (data.length > 0) {
									this.$emit("editCheckAll", false);
								}
								_this.goods = _this.goods.concat(data);
								_this.mescroll.endBySize(data.length, res.data.total);
							}).catch((e) => {
								_this.mescroll.endErr();
								_this.$util.Tips({
									title: e
								});
							});
						}
					}

				});
			},
			editChange(checkStatus) {
				var _this = this;
				_this.goods.map((i) => {
					_this.$set(i, "isSelect", checkStatus);
				});
				this.toggleSelection(1, checkStatus);
			},
			// 单选
			selected(index) {
				var _this = this;
				_this.$set(this.goods[index], "isSelect", !this.goods[index].isSelect);
				this.toggleSelection(0, this.goods[index]);
			},
			toggleSelection(type, item) {
				// 0 单选  1多选
				if (type) {
					if (item) {
						this.goods.map((i) => {
							if (!this.productIdList.includes(i.id)) {
								this.productIdList.push(i.id);
							}
						});
					} else {
						this.productIdList = [];
					}
				} else {
					if (this.productIdList.includes(item.id)) {
						let arr = [];
						this.productIdList.map((i) => {
							if (i != item.id) {
								arr.push(i);
							}
						});
						this.productIdList = arr;
					} else {
						this.productIdList.push(item.id);
					}
				}
				if (this.goods.length > 0) {
					this.productIdList.length == this.goods.length ?
						this.$emit("editCheckAll", true) :
						this.$emit("editCheckAll", false);
				}
			},
			// 专区
			getZhuanQuList() {
				let _this = this;
				zoneList({
					page: 1,
					limit: 9999,
					zoneType: 1,
					endTime: (formatTime(new Date())).toString().replace(/\//g, '-'),
				}).then((res) => {
					_this.zhuanquList = res.data.list;
				}).catch((e) => {
					console.info(e, '报错')
				});
			},
			bindPickerChange: function(e) {
				this.$set(this.zoneData, "idx", e.detail.value);
				this.zoneData.zoneId = this.zhuanquList[e.detail.value].id;
			},
			bindPriceChange: function(e) {
				this.$set(this.priceData, "idx1", e.detail.value);
				if (this.index == 0) {
					this.priceData.type = this.priceType[e.detail.value].id;
				} else {
					this.priceData.type = this.buildAddType[e.detail.value].id;
				}
			},
			// 恢复默认加价率
			productResetPrice() {
				var that = this
				const data = {
					productIdList: this.productIdList,
					productType: this.priceData.productType,
					type: 0,
				};
				uni.showLoading({
					title: that.$t('publicLang.pleaseWait')
				});
				batchUpdatePrice(data).then((res) => {
						uni.hideLoading();
						that.$util.Tips(that.$t('publicLang.successfulOperation'));
						//that.$emit("change", that.current);
						this.priceData.priceShow = false;
						this.editChange(false, 1);
						this.clear(1);
					})
					.catch((err) => {
						uni.hideLoading();
						that.$util.Tips({
							title: e
						});
					});
			},
			// 商品详情页跳转
			goodsDetail(id) {
				if (this.index == 0) {
					uni.navigateTo({
						url: `/pages/goods_detail/index?id=${id}`
					});
				} else {
					uni.navigateTo({
						url: `/pages/creatBuildStore/index?id=${id}`
					});
				}
			},
			// 上下架商品
			putShell(id) {
				var _this = this;
				productIsshow({
					productId: id,
					isNotShow: _this.current ? "0" : "1",
				}).then((res) => {
					uni.showToast({
						title: `${_this.current == 0 ? _this.$t('goods.takeDown') : _this.$t('goods.onTheShelf')}${_this.$t('goods.success')}~`,
						duration: 2000,
					});
					_this.mescroll.resetUpScroll(true);
				}).catch(e => {
					_this.$util.Tips({
						title: e
					});
				});
			},
			bacthRecommend(value) {
				let that = this
				if (value == 0 || value == 1) {
					var data = {
						productIdList: that.productIdList,
						isBest: value,
					};
					batchIsBestApi(data).then((res) => {
						that.$util.Tips({
							title: that.$t("publicLang.successfulOperation")
						});
						//that.$emit("change", that.current);
						this.editChange(false);
						this.show = false
					}).catch((e) => {
						that.$util.Tips({
							title: e,
						});
						this.editChange(false);
						this.show = false
						//that.$emit("change", that.current);
					});
				}
				 // 批量自建转云仓
				if (value == 3) {
					transferCloud(that.productIdList).then((res) => {
						that.$util.Tips({
							title: that.$t("publicLang.successfulOperation")
						});
						//that.$emit("change", that.current);
						this.editChange(false);
						this.show = false
					}).catch((e) => {
						that.$util.Tips({
							title: e,
						});
						this.editChange(false);
						this.show = false
						//that.$emit("change", that.current);
					});
				}
			},
			bacthUpdate(type) {
				var that = this;
				if (that.productIdList.length == 0) {
					that.$util.Tips({
						title: that.$t("goods.pleaseSelectAnItem"),
					});
					return;
				}
				if (type) {
					//批量推荐
					this.show = true
					// var data = {
					// 	productIdList: that.productIdList,
					// 	isBest: 1,
					// };
					// batchIsBestApi(data)
					// 	.then((res) => {
					// 		that.$util.Tips({
					// 			title: that.$t("goods.recommendedSuccess")
					// 		});
					// 		that.$emit("change", that.current);
					// 		this.editChange(false);
					// 	})
					// 	.catch((e) => {
					// 		that.$util.Tips({
					// 			title: e,
					// 		});
					// 		that.$emit("change", that.current);
					// 	});
				} else {
					//批量上下架
					var data = {
						productIdList: that.productIdList,
						isNotShow: this.tableFrom.type == 1 ? "1" : "0",
					};
					batchIsShowApi(data)
						.then((res) => {
							that.$util.Tips({
								title: `${this.tableFrom.type == 1 ? that.$t('goods.takeDown') : that.$t('goods.onTheShelf')}${that.$t('goods.success')}~`,
							});
							//that.$emit("change", that.current);
							this.editChange(false);
						})
						.catch((e) => {
							that.$util.Tips({
								title: e,
							});
							//that.$emit("change", that.current);
						});
				}
			},
			// 加入专区
			addZhuanqu() {
				var that = this;
				var data = {
					productIds: that.productIdList.join(","),
					zoneId: that.zoneData.zoneId,
				};
				zoneProductAdd(data)
					.then((res) => {
						that.$util.Tips({
							title: that.$t("goods.recommendedSuccess")
						});
						//that.$emit("change", that.current);
						this.show = false;
						this.editChange(false);
						this.clear(0);
					})
					.catch((err) => {
						that.$util.Tips({
							title: err,
						});
					});
			},
			zhuanquShow() {
				var that = this;
				if (that.productIdList.length == 0) {
					that.$util.Tips({
						title: that.$t("goods.pleaseSelectAnItem"),
					});
					return;
				}
				this.zoneData.zoneId = this.zhuanquList[0].id;
				this.zoneData.show = !this.zoneData.show;
			},
			// 价格弹窗显示
			batchUpdateShow(id) {
				var that = this;
				if (id) {
					that.productIdList.push(id);
				}
				if (that.productIdList.length == 0) {
					that.$util.Tips({
						title: that.$t("goods.pleaseSelectAnItem")
					});
					return;
				}
				this.priceData.priceShow = !this.priceData.priceShow;
			},
			// 推荐
			onchangeIsBest(row) {
				var that = this;
				merchantStoreProductIsBest({
					productId: row.id,
					isBest: !row.isBest,
				}).then((res) => {
					that.$util.Tips({
						title: that.$t("goods.markingSucceeded")
					});
					row.isBest = !row.isBest
				}).catch((e) => {
					that.$util.Tips({
						title: e
					});
				});
			},
			// 修改价格
			batchPrice() {
				var that = this;
				const data = {
					productIdList: that.productIdList,
					productType: that.priceData.productType,
					ratio: Number(that.priceData.ratio),
					type: that.priceData.type,
				};
				if (data.ratio == null || data.ratio == "") {
					return that.$util.Tips({
						title: that.$t("goods.pleaseEnterMarkupRateDiscount")
					});
				}
				if (data.type == 3 && data.ratio && data.ratio <= -100) {
					that.$util.Tips({
						title: that.$t("goods.markupRateEntryRestrictions")
					});
					return;
				}
				if (data.type == 4 && data.ratio && data.ratio <= 0) {
					that.$util.Tips({
						title: that.$t("goods.originalPriceDiscountEntryRestrictions")
					});
					return;
				}
				batchUpdatePrice(data)
					.then((res) => {
						that.$util.Tips(that.$t("goods.pleaseSelectAnItem"));
						//that.$emit("change", that.current);
						this.priceData.priceShow = false;
						this.editChange(false, 1);
						this.clear(1);
					})
					.catch((err) => {
						that.$util.Tips({
							title: err
						});
					});
			},
			//点击空布局按钮的回调
			emptyClick() {
				uni.showToast({
					title: "点击了按钮,具体逻辑自行实现",
				});
			},
			clear(item) {
				if (item == 0) {
					this.zoneData = {
						zoneData: this.zhuanquList[0].id,
						idx: 0,
						show: false,
					};
				} else {
					this.priceData = {
						productType: 1,
						idx1: 0,
						type: 3,
						ratio: "",
						priceShow: false,
						priceData: null,
					};
				}
			},
			checkInputFun(e) {
				if (e.detail.value.indexOf(".") == 0) {
					console.log('首位小数点情况')
					e.detail.value = e.detail.value.replace(/[^$#$]/g, "0.");
					e.detail.value = e.detail.value.replace(/\.{2,}/g, ".");
				} else if (!(/^(\d?)+(\.\d{0,3})?$/.test(e.detail.value))) {
					//去掉最后一位
					e.detail.value = e.detail.value.substring(0, e.detail.value.length - 1)
				}
				this.$nextTick(function() {
					this.priceData.ratio = e.detail.value
				})
			}
		},
	};
</script>
<style lang="scss" scoped>
	.popup {
		.title {
			font-size: 32rpx;
			padding: 30rpx;
			border-bottom: 1rpx solid #f5f5f5;
		}

		.type {
			display: flex;
			align-items: center;
			padding: 20rpx;

			.picker {
				width: 300rpx;
				padding: 10rpx 15rpx;
				border: 1rpx solid #cecdcd;
				position: relative;

				.iconfont {
					position: absolute;
					right: 10rpx;
					line-height: 20rpx;
					font-size: 21rpx;
				}
			}
		}

		.picker {
			width: 400rpx;
			padding: 10rpx 0rpx;
			border: 1rpx solid #cecdcd;
			position: relative;
			font-size: 30rpx;

			.reason {
				padding: 0rpx 6rpx;
			}

			.iconfont {
				position: absolute;
				right: 10rpx;
				line-height: 20rpx;
				font-size: 21rpx;
			}
		}
	}

	.ratio {
		padding: 20rpx;

		.uni-input {
			border: 1rpx solid #cecdcd;
			padding: 10rpx 5rpx;
		}

		.reason {
			color: red;
			padding: 5rpx;
		}
	}

	.btntype {
		display: flex;
		justify-content: space-around;
		padding: 20rpx 0rpx;

		.btn {
			padding: 10rpx 24rpx;
			border: 1rpx solid rgb(29, 28, 28);
			border-radius: 10rpx;
			margin: 0rpx 5rpx;
		}

		.btn.pushBtn {
			background: black;
			color: #ffffff;
		}
	}

	.batchButton {
		padding: 20rpx 0;
		text-align: center;
		border-bottom: 1rpx solid #dadada;
	}
</style>
